package com.webmining.sherlock.web;

import com.webmining.sherlock.search.Result;
import com.webmining.sherlock.search.Search;
import com.webmining.sherlock.search.SearchException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class SearchServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String queryString = req.getParameter("query");

        if (queryString == null) {
            queryString = "";
        }
        queryString = new String(queryString.getBytes("ISO-8859-1"), "UTF-8");

        try {
            Search search = new Search(queryString);
            if (search.getTotalDocumentsInIndex() == 0) {
                req.setAttribute("noDocumentsIndexed", true);
            }
            else{
                int totalResults = search.getTotalResults();
                if (totalResults == 0) {
                    req.setAttribute("totalResults", totalResults);
                } else {
                    // Reads the start index or begin at 0 by default
                    int startIndex = 0;
                    String startIndexString = req.getParameter("start");
                    if (startIndexString != null) {
                        startIndex = Integer.parseInt(startIndexString);
                    }
                    if (startIndex > totalResults) {
                        startIndex = 0;
                    }
                    // Reads the max results per page, defaults to 25
                    int maxResultsPerPage= 25;
                    String maxResultsPerPageString =
                            req.getParameter("maxresultsperpage");
                    if (maxResultsPerPageString != null) {
                        maxResultsPerPage = Integer.parseInt(
                                maxResultsPerPageString);
                    }
                    // Calculate the endIndex
                    int endIndex = startIndex + maxResultsPerPage;
                    if (endIndex > totalResults) {
                        endIndex = totalResults;
                    }
                    // Display the results
                    List<Result> results = new ArrayList<>();
                    for (int i=startIndex; i < endIndex; i++) {
                        Result result = new Result();
                        result.setTitle(search.getTitle(i));
                        result.setUrl(search.getUrl(i));
                        result.setSummary(search.getSummary(i));
                        result.setContent(search.getContent(i));

                        results.add(result);
                    }
                    req.setAttribute("results", results);

                    // Display a basic navigation bar
                    String previousURL = null;
                    String nextURL = null;
                    String queryStringEncoded = URLEncoder.encode(queryString);
                    String baseURL = req.getRequestURI() + "?query=" +
                            queryStringEncoded + "&maxresultsperpage=" +
                            maxResultsPerPage;
                    if (startIndex > 0) {
                        int previousIndex = startIndex - maxResultsPerPage;
                        if (previousIndex < 0) {
                            previousIndex = 0;
                        }
                        previousURL = baseURL + "&start=" + previousIndex;
                    }
                    int nextIndex = startIndex + maxResultsPerPage;
                    if (nextIndex < totalResults) {
                        nextURL = baseURL + "&start=" + nextIndex;
                    }

                    req.setAttribute("nextURL", nextURL);
                    req.setAttribute("previousURL", previousURL);
                    req.setAttribute("maxResultsPerPage", maxResultsPerPage);

                }
            }
        } catch (SearchException se) {
            req.setAttribute("error", true);
        }
        getServletContext().getRequestDispatcher("/results.jsp").forward(req, resp);
    }
}
